﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cosmetic.DataEntity;
using System.Collections;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace Cosmetic.Logic
{
    /// <summary>
    /// 
    /// </summary>
    public class IntegralManager : LogicBase
    {


        #region 积分
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public IEnumerable GetIntegralLog()
        {
            var result = from integral in m_CosmeticDC.IntegralSettings
                         select integral;
            return result;
        }

        public void WriteIntegralLog(DateTime starttime, DateTime endtime, decimal integral, decimal coefficient, Guid SupCategoryId, Guid CategoryId, Guid SubCategoryId)
        {
            var aProducts = (from pt in m_CosmeticDC.Products
                             where pt.ProductCategoryId == SubCategoryId
                             select pt).ToList();

            foreach (Product prd in aProducts)
            {
                prd.Integral = integral;
                prd.coefficient = coefficient;
            }

            IntegralSetting InSetting = new IntegralSetting();
            InSetting.Id = Guid.NewGuid();
            InSetting.Integral = integral;
            InSetting.Coefficient = coefficient;
            InSetting.StartDate = starttime;
            InSetting.EndDate = endtime;
            InSetting.SupCategoryId = SupCategoryId;
            InSetting.CategoryId = CategoryId;
            InSetting.SubCategoryId = SubCategoryId;

            m_CosmeticDC.IntegralSettings.InsertOnSubmit(InSetting);

            m_CosmeticDC.SubmitChanges();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <param name="integral"></param>
        /// <param name="coefficient"></param>
        /// <param name="SupCategoryId"></param>
        /// <param name="CategoryId"></param>
        public void WriteIntegralLog(DateTime starttime, DateTime endtime, decimal integral, decimal coefficient, Guid SupCategoryId, Guid CategoryId)
        {

            //update product with integral and coefficient

            var aProducts = (from pt in m_CosmeticDC.Products
                             where pt.ProductCategoryId == CategoryId
                             select pt).ToList();

            foreach (Product prd in aProducts)
            {
                prd.Integral = integral;
                prd.coefficient = coefficient;
            }

            //insert log
            IntegralSetting InSetting = new IntegralSetting();
            InSetting.Id = Guid.NewGuid();
            InSetting.Integral = integral;
            InSetting.Coefficient = coefficient;
            InSetting.StartDate = starttime;
            InSetting.EndDate = endtime;
            InSetting.SupCategoryId = SupCategoryId;
            InSetting.CategoryId = CategoryId;

            m_CosmeticDC.IntegralSettings.InsertOnSubmit(InSetting);

            m_CosmeticDC.SubmitChanges();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <param name="integral"></param>
        /// <param name="coefficient"></param>
        /// <param name="SupCategoryId"></param>
        public void WriteIntegralLog(DateTime starttime, DateTime endtime, decimal integral, decimal coefficient, Guid SupCategoryId)
        {
            var aProducts = (from pt in m_CosmeticDC.Products
                             where pt.ProductCategoryId == SupCategoryId
                             select pt).ToList();

            foreach (Product prd in aProducts)
            {
                prd.Integral = integral;
                prd.coefficient = coefficient;
            }


            IntegralSetting InSetting = new IntegralSetting();
            InSetting.Id = Guid.NewGuid();
            InSetting.Integral = integral;
            InSetting.Coefficient = coefficient;
            InSetting.StartDate = starttime;
            InSetting.EndDate = endtime;
            InSetting.SupCategoryId = SupCategoryId;

            m_CosmeticDC.IntegralSettings.InsertOnSubmit(InSetting);

            m_CosmeticDC.SubmitChanges();
        }
        #endregion


        #region 优尤卡

        /// <summary>
        /// 绑定用户
        /// </summary>
        /// <param name="CardNum"></param>
        /// <param name="userId"></param>
        public void BindUser(string CardNum, Guid userId, string ValidateCode)
        {

            var result = from cc in m_CosmeticDC.CashCard
                         where cc.CardNum == CardNum
                         select cc;
            if (result.Count() == 0)
            {
                throw new Exception("该卡号不存在");
            }
            if (result.Single().ValidateCode != ValidateCode)
            {
                throw new Exception("验证码不正确");
            }

            CashCard CC = result.Single();
            CC.UserId = userId;

            //User us = (from user in m_CosmeticDC.Users
            //           where user.UserId == userId
            //           select user).Single();

            m_CosmeticDC.SubmitChanges();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="CardNum"></param>
        /// <returns></returns>
        public List<CashCardUseLog> GetCardLog(string CardNum)
        {
            var result = (from cardlog in m_CosmeticDC.CashCardUseLogs
                          where cardlog.CardNum == CardNum
                          select cardlog).ToList();
            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="CardNum"></param>
        /// <returns></returns>
        public CashCard GetCashCard(string CardNum)
        {
            var result = (from card in m_CosmeticDC.CashCard
                          where card.CardNum == CardNum
                          select card);
            return result.Single();

            //IEnumerable<CashCard> cashcards = m_CosmeticDC.ExecuteQuery<CashCard>("select * from CashCard where CardNum = "+CardNum);

            //return cashcards.ToList().Single();
            //return m_CosmeticDC.CashCards.Where(c=>c.CardNum==CardNum).Single();
        }

        /// <summary>
        /// 后台生成 jj-9卡号
        /// </summary>
        /// <param name="Capital">卡号开头的2个字母</param>
        /// <param name="count">生成个数</param>
        public void InsertCashCard(string Capital, int count)
        {
            string CurrentMaxCardNo = "";

            for (int i = 0; i < count; i++)
            {
                CurrentMaxCardNo = (from cmcn in m_CosmeticDC.CashCard
                                    select cmcn).Max(c => c.CardNum);
                CashCard cc = new CashCard();
                cc.CardNum = Capital + (int.Parse(CurrentMaxCardNo.Substring(2)) + 1).ToString();
                m_CosmeticDC.CashCard.InsertOnSubmit(cc);
            }
            m_CosmeticDC.SubmitChanges();
        }

        /// <summary>
        /// 获得当前用户的 jj-9卡
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        //public IEnumerable GetCardInfoByUser(Guid userId)
        //{
        //    //<asp:BoundField HeaderText="时间" DataField=""/>
        //    //<asp:BoundField HeaderText="接受人" DataField="" />
        //    //<asp:BoundField HeaderText="优尤卡号"  DataField="" />
        //    //<asp:BoundField HeaderText="优尤卡金额" DataField="" />
        //    //<asp:BoundField HeaderText="状态" DataField="" />


        //    var result = from cc in m_CosmeticDC.CashCard 
        //                 where cc.UserId == userId
        //                 select new
        //                 {
        //                     CreateTime = cc.ctime.ToLocalTime(),
        //                     UserName = (from user in m_CosmeticDC.Users where user.UserId == userId select user.UserName).Single(),
        //                     CardNum = cc.CardNum,
        //                     Balance = cc.balance,
        //                     ExpireTime = cc.ExpireTime,
        //                     State = "",

        //                 };
        //    return result;
        //}

        //public IEnumerable GetAvailbleCardInfoByUserId(Guid UserId)
        //{
        //    var resut = from cc in m_CosmeticDC.CashCard 
        //                where cc.UserId == UserId && cc.balance > 0
        //                select new
        //                {
        //                    CreateTime = cc.ctime.ToLocalTime(),
        //                    UserName = (from user in m_CosmeticDC.Users where user.UserId == UserId select user.UserName).Single(),
        //                    CardNum = cc.CardNum,
        //                    Balance = cc.balance,
        //                    ExpireTime = cc.ExpireTime,
        //                    State = "",

        //                };
        //    return resut;

        //}


        //扣优惠券
        public void UseDiscountCard(Order aOrder)
        {
            if (aOrder.UsedDiscountCardId != "")
            {
                var result = (from discard in m_CosmeticDC.DiscountCards
                              where discard.Id == aOrder.UsedDiscountCardId
                              select discard).Single();
                result.IsUsed = true;
                m_CosmeticDC.SubmitChanges();
            }
        }

        //扣悠悠卡

        public void UseCashCard(Order aOrder)
        {
            if (aOrder.UsedCashCardId != "")
            {
                var result = (from cashcard in m_CosmeticDC.CashCard
                              where cashcard.CardNum == aOrder.UsedCashCardId
                              select cashcard).Single();
                result.balance = result.balance - aOrder.UseCashCard.Value;


                CashCardUseLog cardlog = new CashCardUseLog();
                cardlog.CreateTime = DateTime.Now;
                cardlog.CardNum = result.CardNum;
                cardlog.Balance = result.balance;
                cardlog.OrderNum = aOrder.OrderNum;
                cardlog.OrderId = aOrder.OrderId;
                cardlog.UserId = aOrder.UserId;
                cardlog.UsedAmount = aOrder.UseCashCard;
                m_CosmeticDC.CashCardUseLogs.InsertOnSubmit(cardlog);

                m_CosmeticDC.SubmitChanges();
            }

        }

        #endregion

        static string conStr = ConfigurationManager.ConnectionStrings["CosmeticConnectionString"].ConnectionString;

        /// <summary>
        /// 获得积分。
        /// </summary>
        public static string SelectIntegral()
        {
            SqlConnection con = new SqlConnection(conStr);
            try
            {
                con.Open();
                string cmdStr = "select Integral from dbo.UserIntegral ";
                SqlCommand com = new SqlCommand(cmdStr, con);
                return com.ExecuteScalar().ToString();
            }
            finally
            {
                con.Close();
            }
        }

        /// <summary>
        /// 更新积分。
        /// </summary>
        public static void UpdateIntegral(int integral)
        {
            SqlConnection con = new SqlConnection(conStr);
            try
            {
                con.Open();
                string cmdStr = "update dbo.UserIntegral set Integral =" + integral + " ";
                SqlCommand com = new SqlCommand(cmdStr, con);
                com.ExecuteNonQuery();
            }
            finally
            {
                con.Close();
            }
        }


        public IEnumerable GetiProductList()
        {
            var result = from theiProduct in m_CosmeticDC.iProducts
                         join theProduct in m_CosmeticDC.Products
                         on theiProduct.ProductId equals theProduct.ProductId
                         orderby theiProduct.Sequence ascending
                         select new
                         {
                             Id = theiProduct.Id,
                             ProductId = theProduct.ProductId,
                             Name = theProduct.Name,
                             Views = theProduct.Views,
                             PicUrl = theProduct.PictureUrl,
                             Sequence = theiProduct.Sequence,
                             Price = theProduct.Price,
                             eprice = theProduct.eprice,
                             Description = theProduct.Description,
                             Comments = theProduct.Comments.Count,
                             Point = theiProduct.Point
                         };
            return result;
        }

        public DataTable GetiProduct()
        {
            SqlConnection con = new SqlConnection(conStr);
            try
            {
                con.Open();
                DataSet ds = new DataSet();

                string cmdStr = "select * from dbo.iProduct a join dbo.Product b on a.ProductId = b.ProductId order by a.Sequence";
                SqlDataAdapter adap = new SqlDataAdapter();

                SqlCommand com = new SqlCommand(cmdStr, con);

                adap.SelectCommand = com;
                adap.Fill(ds);
                return ds.Tables[0];
            }
            finally
            {
                con.Close();
            }
        }

        public void InsertiProduct(string ProductId, int Sequence, decimal Point)
        {
            SqlConnection con = new SqlConnection(conStr);
            try
            {
                con.Open();
                string cmdStr = string.Format("insert into dbo.iProduct (Id, ProductId, Sequence, CreateTime,Point) values('{0}','{1}','{2}','{3}','{4}') ", Guid.NewGuid().ToString(), ProductId, Sequence, DateTime.Now, Point);
                SqlCommand com = new SqlCommand(cmdStr, con);
                com.ExecuteNonQuery();
            }
            finally
            {
                con.Close();
            }
        }


        public void DeleteiProduct(string Id)
        {
            SqlConnection con = new SqlConnection(conStr);
            try
            {
                con.Open();
                string cmdStr = string.Format("delete from dbo.iProduct where Id = '{0}'", Id);
                SqlCommand com = new SqlCommand(cmdStr, con);
                com.ExecuteNonQuery();
            }
            finally
            {
                con.Close();
            }
        }
    }
}
